package 在排序数组中查找元素的第一个和最后一个位置;

public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] ints = {6};
        int target = 6;
        int[] ints1 = solution.searchRange(ints, target);
        System.out.println(ints1[0]);
        System.out.println(ints1[1]);
    }
    public int[] searchRange(int[] nums, int target) {
        int l = 0;
        int r = nums.length - 1;

        int index = -1;
        while(l <= r){
            int half = (l + r) / 2;
            if(nums[half] ==  target){
                index = half;
                break;
            }
            if(target > nums[half]   ){
                l = half + 1;
            }
            else{
                r = half - 1;
            }
        }

        if(index == -1){
            return new int[]{-1,-1};
        }
        else{
            int left = index, right = index;
            while(left != 0 && nums[left-1] == target){
                left--;
            }
            while(right != nums.length -1 && nums[right+1] == target){
                right++;
            }
            return new int[]{left,right};
        }
    }
}
